from .token_manager import TokenManager
import requests
from django.conf import settings
import logging

logger = logging.getLogger(__name__)

class EbayService:
    def __init__(self):
        self.token_manager = TokenManager()
        self.base_url = "https://api.ebay.com"
        self.headers = {
            'Content-Type': 'application/json'
        }

    def _get_headers(self):
        """获取带有认证信息的请求头"""
        access_token = self.token_manager.get_token()
        if not access_token:
            raise Exception("无法获取有效的访问令牌")
        
        headers = self.headers.copy()
        headers['Authorization'] = f'Bearer {access_token}'
        return headers

    def get_account_info(self):
        """获取账户信息"""
        try:
            response = requests.get(
                f"{self.base_url}/sell/account/v1/privilege",
                headers=self._get_headers()
            )
            response.raise_for_status()
            return response.json()
        except Exception as e:
            logger.error(f"获取账户信息失败: {e}")
            raise

    def get_inventory_items(self, limit=100, offset=0):
        """获取库存商品列表"""
        try:
            response = requests.get(
                f"{self.base_url}/sell/inventory/v1/inventory_item",
                headers=self._get_headers(),
                params={'limit': limit, 'offset': offset}
            )
            response.raise_for_status()
            return response.json()
        except Exception as e:
            logger.error(f"获取库存商品失败: {e}")
            raise

    def update_inventory_item(self, sku, data):
        """更新库存商品信息"""
        try:
            response = requests.put(
                f"{self.base_url}/sell/inventory/v1/inventory_item/{sku}",
                headers=self._get_headers(),
                json=data
            )
            response.raise_for_status()
            return response.json()
        except Exception as e:
            logger.error(f"更新库存商品失败: {e}")
            raise

    def get_orders(self, limit=100, offset=0):
        """获取订单列表"""
        try:
            response = requests.get(
                f"{self.base_url}/sell/fulfillment/v1/order",
                headers=self._get_headers(),
                params={'limit': limit, 'offset': offset}
            )
            response.raise_for_status()
            return response.json()
        except Exception as e:
            logger.error(f"获取订单列表失败: {e}")
            raise

    def get_order_details(self, order_id):
        """获取订单详情"""
        try:
            response = requests.get(
                f"{self.base_url}/sell/fulfillment/v1/order/{order_id}",
                headers=self._get_headers()
            )
            response.raise_for_status()
            return response.json()
        except Exception as e:
            logger.error(f"获取订单详情失败: {e}")
            raise

    def update_order_status(self, order_id, status_data):
        """更新订单状态"""
        try:
            response = requests.post(
                f"{self.base_url}/sell/fulfillment/v1/order/{order_id}/shipping_fulfillment",
                headers=self._get_headers(),
                json=status_data
            )
            response.raise_for_status()
            return response.json()
        except Exception as e:
            logger.error(f"更新订单状态失败: {e}")
            raise

    def get_token_status(self):
        """获取令牌状态信息"""
        return self.token_manager.get_token_info()

# 创建单例实例
ebay_service = EbayService() 